package protocol;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import statter.Stats;

public class CommSckServerIn implements Runnable {
	private int port;
	private CommandRelay cmdRly;
	private Thread thread;
	private ServerSocket sSckt;
	private Socket sckt;
	private ObjectInputStream is;
	private Stats statter;
	
	public CommSckServerIn(CommandRelay cmdRly, Stats statter) {
		this(11167,cmdRly, statter);
	}

	public CommSckServerIn(int port, CommandRelay cmdRly, Stats statter) {
		this.statter = statter;
		this.statter.addSection("Incoming tcp thread");
		this.port = port;
		this.cmdRly = cmdRly;
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		try {
			sSckt = new ServerSocket(port);
			sckt = sSckt.accept();
			is = new ObjectInputStream(sckt.getInputStream());
			while(sckt.isConnected()) {
				statter.statStart("Incoming tcp thread");
				cmdRly.addInCmd((Cmd)is.readObject());
				statter.statEnd("Incoming tcp thread");
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
